#!/bin/bash

# Function to increment the version number in pubspec.yaml
increment_version() {
  # Read the current version from pubspec.yaml
  current_version=$(grep -E '^version: ' pubspec.yaml | awk '{print $2}')
  
  # Extract the major, minor, patch, and build numbers
  version_number=$(echo $current_version | cut -d "+" -f1)
  build_number=$(echo $current_version | cut -d "+" -f2)
  major=$(echo $version_number | cut -d "." -f1)
  minor=$(echo $version_number | cut -d "." -f2)
  patch=$(echo $version_number | cut -d "." -f3)
  
  # Increment the patch and build numbers
  new_patch=$((patch + 1))
  new_build=$((build_number + 1))
  new_version="$major.$minor.$new_patch+$new_build"
  
  # Update the version in pubspec.yaml
  sed -i '' "s/^version: .*/version: $new_version/" pubspec.yaml

  echo "Version updated to $new_version"
}

# Check for the -r flag
revert_flag=0
while getopts "r" opt; do
  case $opt in
    r) revert_flag=1 ;;
    *) echo "Usage: $0 [-r]"; exit 1 ;;
  esac
done

# Backup the current version
current_version=$(grep -E '^version: ' pubspec.yaml | awk '{print $2}')
if [ $revert_flag -eq 0 ]; then
  increment_version
fi

# Clean and build the Flutter project
flutter clean && flutter build appbundle --flavor prod -t lib/main_prod.dart --verbose --no-tree-shake-icons
build_status=$?

if [ $build_status -ne 0 ]; then
  echo "Build failed"
  if [ $revert_flag -eq 0 ]; then
    # Revert to the original version
    sed -i '' "s/^version: .*/version: $current_version/" pubspec.yaml
    echo "Version reverted to $current_version"
  fi
  exit $build_status
fi

echo "Build succeeded"
